<?php

namespace App\Http\Controllers;


use App\Model\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function getLogin(Request $request)
    {
//        $auto_login = $request->cookie('auto_login');
//        if ($auto_login) {
//            $password = substr($auto_login, 0, 32);
//            $name = substr($auto_login, 32, strlen($auto_login) - 32);
//            $name = base64_decode($name);
//            $user = User::where('name', $name)->first();
//            if ($user && $password == $user->password) {
//                session()->put('user', $user->toArray());
////                session('user',$user->toArray());
//                return redirect('/auth/login-success');
//            }
//        }
        return view('auth.login');
    }



    public function postLogin(Request $request)
    {

        $name = $request->input('name');
        $password = $request->input('password');

        $password = strtoupper(md5($password));
        $user = User::where('name', $name)->first();
        if (!$user) {
            return $this->json_error('用户不存在', 1000);
        }
        if ($password != $user->password) {
            return $this->json_error('密码不正确', 1001);
        }

        $auto_login = $password . base64_encode($name);

        session()->put('user', $user->toArray());

        return $this->json_success($user->toArray())->withCookie('auto_login', $auto_login, 60 * 24 * 15, '/');

    }

    public function getLogout()
    {
        session()->clear();
        return redirect('/auth/login')->withCookie('auto_login', '', -60 * 24, '/');
    }

    public function getRegister()
    {
        //TODO
    }

    public function postRegister()
    {
        //TODO
    }

    public function getLoginSuccess()
    {
        $user = $this->_getCurrentUser();
        if ($user->is_admin) {
            return redirect('/admin');
        } else {
            return redirect('/frontend');
        }
    }

}
